package com.abbas.smartCity.base;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.abbas.smartCity.App;
import com.abbas.smartCity.retroft.Api;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * fragment基础封装
 */
public abstract class BaseFragment extends Fragment {

    /**
     * retrofit动态代理接口
     */
    protected final Api api = App.getApi();
    protected static final Gson gson = App.gson;

    /**
     * 当前页面的视图
     */
    protected View rootView = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        rootView = inflater.inflate(getLayoutId(),container,false);

        initView();
        initData();
        initEvent();

        return rootView;
    }

    /**
     * 获取布局ID
     * @return 布局ID
     */
    protected abstract int getLayoutId();

    /**
     * 寻找控件、控件操作
     */
    protected abstract void initView();

    /**
     * 数据操作、网络操作
     */
    protected abstract void initData();

    /**
     * 监听设置、事件设置
     */
    protected abstract void initEvent();

    protected <T> void startActivity(Class<T> targetClazz){
        startActivity(new Intent(requireActivity(),targetClazz));
    }

    protected void showToast(String tip){
        Toast.makeText(requireContext(),tip,Toast.LENGTH_SHORT).show();
    }


    /**
     * 获取一个HashMap
     * @return HashMap
     */
    protected static Map<String, Object> getMap(){
        return new HashMap<>();
    }

    /**
     * 获取一个RequestBody
     * @param paramsMap 需要放入RequestBody的键值对Map数据
     * @return RequestBody
     */
    protected static RequestBody createRequestBody(Map<String,Object> paramsMap){
        return RequestBody.create(MediaType.parse("application/json"),gson.toJson(paramsMap));
    }

    /**
     * 获取一个RequestBody
     * @param paramsObj 需要放入RequestBody的数据对象
     * @return RequestBody
     */
    protected static RequestBody createRequestBody(Object paramsObj){
        return RequestBody.create(MediaType.parse("application/json"),gson.toJson(paramsObj));
    }

}
